package zbase;

import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

public class EditZDialog extends javax.swing.JDialog {

    private z_Z zzo = null;

    public EditZDialog(java.awt.Frame parent, boolean modal, z_Z zz) {
        super(parent, modal);
        initComponents();
        zzo = zz;
        this.setMinimumSize(this.getSize());
        FillAll();
        if (!Vars.obj_User.CanObjects) {
            jComboBox1.setEditable(false);
            jButton3.setEnabled(false);
        }
        if (!Vars.obj_User.CanServices) {
            jComboBox2.setEditable(false);
            jButton4.setEnabled(false);
        }
        if (!Vars.obj_User.CanZmain) {
            jButton1.setEnabled(false);
        }
    }

    private void FillAll() {
        jLabel1.setText("Заявка № " + zzo.getK().toString());
        SimpleDateFormat sdfd = new SimpleDateFormat("dd.MM.yyyy");
        SimpleDateFormat sdft = new SimpleDateFormat("HH:mm");
        jFormattedTextField1.setText(sdfd.format(zzo.getZdatetime().getTime()));
        jFormattedTextField2.setText(sdft.format(zzo.getZdatetime().getTime()));

        RefreshObjects();
        RefreshServices();

        jTextArea1.setText(zzo.getZtext());
        jTextArea2.setText(zzo.getZprim());

        if (zzo.isZalert()) {
            jCheckBox2.setSelected(true);
        } else {
            jCheckBox2.setSelected(false);
        }

        if (zzo.isZdone()) {
            jCheckBox1.setSelected(true);
            jLabel6.setEnabled(true);
            jFormattedTextField3.setEnabled(true);
            jFormattedTextField4.setEnabled(true);
            Calendar tc = (Calendar) zzo.getZdatetime().clone();
            tc.add(Calendar.DAY_OF_YEAR, -1);
            if (zzo.getZdonedt().after(tc)) {
                jFormattedTextField3.setText(sdfd.format(zzo.getZdonedt().getTime()));
                jFormattedTextField4.setText(sdft.format(zzo.getZdonedt().getTime()));
                if (jFormattedTextField4.getText().equals("00:00")) {
                    jFormattedTextField4.setText(null);
                }
            }
        } else {
            jCheckBox1.setSelected(false);
            jLabel6.setEnabled(false);
            jFormattedTextField3.setEnabled(false);
            jFormattedTextField4.setEnabled(false);
            jFormattedTextField3.setText(null);
            jFormattedTextField4.setText(null);
        }
    }

    private void RefreshObjects() {
        DB db = new DB();
        ResultSet rs = db.getResultSet("SELECT k, objname FROM objects WHERE hide = 0");
        DefaultComboBoxModel cbm = new DefaultComboBoxModel();
        try {
            while (rs.next()) {
                cbm.addElement(new z_Object(rs.getInt("k"), Vars.getStringFromHex(rs.getString("objname"))));
            }
        } catch (SQLException ex) {
            Logger.getLogger(ObjectsDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
        db.closeResultSet();
        jComboBox1.setModel(cbm);
        jComboBox1.setSelectedIndex(-1);
        for (int i = 0; i < cbm.getSize(); i++) {
            z_Object tzo = (z_Object) cbm.getElementAt(i);
            if (tzo.getK().equals(zzo.getZobject())) {
                jComboBox1.setSelectedItem(tzo);
            }
        }
        if (jComboBox1.getSelectedIndex() == -1) {
            String s = (String) db.getScalar("SELECT objname FROM objects WHERE k = " + zzo.getZobject().toString());
            s = Vars.getStringFromHex(s);
            jComboBox1.setSelectedItem(s);
        }
    }

    private void RefreshServices() {
        DB db = new DB();
        ResultSet rs = db.getResultSet("SELECT k, servicename FROM services WHERE hide = 0");
        DefaultComboBoxModel cbm = new DefaultComboBoxModel();
        try {
            while (rs.next()) {
                cbm.addElement(new z_Service(rs.getInt("k"), Vars.getStringFromHex(rs.getString("servicename"))));
            }
        } catch (SQLException ex) {
            Logger.getLogger(NewZDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
        db.closeResultSet();
        jComboBox2.setModel(cbm);
        jComboBox2.setSelectedIndex(-1);
        for (int i = 0; i < cbm.getSize(); i++) {
            z_Service tzs = (z_Service) cbm.getElementAt(i);
            if (tzs.getK().equals(zzo.getZservice())) {
                jComboBox2.setSelectedItem(tzs);
            }
        }
        if (jComboBox2.getSelectedIndex() == -1) {
            String s = (String) db.getScalar("SELECT servicename FROM services WHERE k = " + zzo.getZservice().toString());
            s = Vars.getStringFromHex(s);
            jComboBox2.setSelectedItem(s);
        }
    }

    private Boolean ValidateData(String dtstr) {
        try {
            int day = Integer.parseInt(dtstr.substring(0, 2));
            if (day > 31 || day == 0) {
                return false;
            }
            int month = Integer.parseInt(dtstr.substring(3, 5));
            month--;
            if (month > 11 || month == -1) {
                return false;
            }
            int year = Integer.parseInt(dtstr.substring(6, 10));
        } catch (NumberFormatException ex) {
        }
        return true;
    }

    private Boolean ValidateTime(String timstr) {
        try {
            int hour = Integer.parseInt(timstr.substring(0, 2));
            if (hour > 23) {
                return false;
            }
            int min = Integer.parseInt(timstr.substring(3, 5));
            if (min > 59) {
                return false;
            }
        } catch (NumberFormatException ex) {
        }
        return true;
    }

    private Calendar ParseDT(String datestr, String timestr) {
        int year = 0;
        int month = 0;
        int day = 0;
        int hour = 0;
        int min = 0;

        try {
            day = Integer.parseInt(datestr.substring(0, 2));
            if (day > 31 || day == 0) {
                return null;
            }
            month = Integer.parseInt(datestr.substring(3, 5));
            month--;
            if (month > 11 || month == -1) {
                return null;
            }
            year = Integer.parseInt(datestr.substring(6, 10));
            hour = Integer.parseInt(timestr.substring(0, 2));
            if (hour > 23) {
                return null;
            }
            min = Integer.parseInt(timestr.substring(3, 5));
            if (min > 59) {
                return null;
            }
        } catch (NumberFormatException ex) {
            return null;
        }

        Calendar calendar = new GregorianCalendar(year, month, day, hour, min);
        return calendar;
    }

    private String getDBTime(Calendar calendar) {
        String year = String.valueOf(calendar.get(Calendar.YEAR));
        String month = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        if (month.length() < 2) {
            month = "0" + month;
        }
        String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
        if (day.length() < 2) {
            day = "0" + day;
        }
        String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
        if (hour.length() < 2) {
            hour = "0" + hour;
        }
        String minute = String.valueOf(calendar.get(Calendar.MINUTE));
        if (minute.length() < 2) {
            minute = "0" + minute;
        }
        return "'" + year + "-" + month + "-" + day + " " + hour + ":" + minute + ":00.0'";
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jFormattedTextField2 = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton3 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        jComboBox2 = new javax.swing.JComboBox();
        jButton4 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jCheckBox2 = new javax.swing.JCheckBox();
        jSeparator1 = new javax.swing.JSeparator();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel6 = new javax.swing.JLabel();
        jFormattedTextField3 = new javax.swing.JFormattedTextField();
        jFormattedTextField4 = new javax.swing.JFormattedTextField();
        jSeparator2 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Правка заявки");

        jLabel1.setText("Заявка №");

        jLabel2.setText("От");

        try {
            jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.##.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField1.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jFormattedTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField1FocusLost(evt);
            }
        });

        try {
            jFormattedTextField2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField2.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jFormattedTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField2FocusLost(evt);
            }
        });

        jLabel3.setText("Объект:");

        jComboBox1.setEditable(true);

        jButton3.setText("...");
        jButton3.setFocusable(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel4.setText("Текст заявки:");

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextArea1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTextArea1);

        jLabel5.setText("Служба:");

        jComboBox2.setEditable(true);

        jButton4.setText("...");
        jButton4.setFocusable(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel7.setText("Примечания:");

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jTextArea2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextArea2KeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(jTextArea2);

        jCheckBox2.setText("Отметка об особом внимании");

        jCheckBox1.setText("Отметка о выполнении");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jLabel6.setText("Дата и время выполнения:");
        jLabel6.setEnabled(false);

        try {
            jFormattedTextField3.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.##.####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField3.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jFormattedTextField3.setEnabled(false);
        jFormattedTextField3.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField3FocusLost(evt);
            }
        });

        try {
            jFormattedTextField4.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jFormattedTextField4.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jFormattedTextField4.setEnabled(false);
        jFormattedTextField4.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField4FocusLost(evt);
            }
        });

        jButton1.setText("Сохранить");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Закрыть");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton5.setText("Отменить изменения");
        jButton5.setFocusable(false);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jCheckBox2)
                    .addComponent(jLabel1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(10, 10, 10)
                        .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton4))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 605, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jCheckBox1)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 715, Short.MAX_VALUE)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 715, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 325, Short.MAX_VALUE)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCheckBox2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jCheckBox1)
                    .addComponent(jLabel6)
                    .addComponent(jFormattedTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)
                    .addComponent(jButton5))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jFormattedTextField1FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField1FocusLost
        if (!ValidateData(jFormattedTextField1.getText())) {
            JOptionPane.showMessageDialog(null, "Ошибка в дате поступления заявки.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
            jFormattedTextField1.setText(sdf.format(zzo.getZdatetime().getTime()));
        }
}//GEN-LAST:event_jFormattedTextField1FocusLost

    private void jFormattedTextField2FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField2FocusLost
        if (!ValidateTime(jFormattedTextField2.getText())) {
            JOptionPane.showMessageDialog(null, "Ошибка во времени поступления заявки.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            jFormattedTextField2.setText(sdf.format(zzo.getZdatetime().getTime()));
        }
}//GEN-LAST:event_jFormattedTextField2FocusLost

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ObjectsDialog dlg = new ObjectsDialog(null, true);
        dlg.setLocationRelativeTo(null);
        dlg.setVisible(true);
        RefreshObjects();
}//GEN-LAST:event_jButton3ActionPerformed

    private void jTextArea1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextArea1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_TAB) {
            evt.consume();
            jComboBox2.requestFocus();
        }
}//GEN-LAST:event_jTextArea1KeyPressed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        ServicesDialog dlg = new ServicesDialog(null, true);
        dlg.setLocationRelativeTo(null);
        dlg.setVisible(true);
        RefreshServices();
}//GEN-LAST:event_jButton4ActionPerformed

    private void jTextArea2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextArea2KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_TAB) {
            evt.consume();
            jCheckBox2.requestFocus();
        }
}//GEN-LAST:event_jTextArea2KeyPressed

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        if (jCheckBox1.isSelected()) {
            jLabel6.setEnabled(true);
            jFormattedTextField3.setEnabled(true);
            jFormattedTextField4.setEnabled(true);
        } else {
            jLabel6.setEnabled(false);
            jFormattedTextField3.setEnabled(false);
            jFormattedTextField4.setEnabled(false);
        }
}//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jFormattedTextField3FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField3FocusLost
        if (!ValidateData(jFormattedTextField3.getText())) {
            JOptionPane.showMessageDialog(null, "Ошибка в дате выполнения заявки.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
            jFormattedTextField3.setText(sdf.format(Calendar.getInstance().getTime()));
        }
}//GEN-LAST:event_jFormattedTextField3FocusLost

    private void jFormattedTextField4FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField4FocusLost
        if (!ValidateTime(jFormattedTextField4.getText())) {
            JOptionPane.showMessageDialog(null, "Ошибка во времени выполнения заявки.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            jFormattedTextField4.setText(sdf.format(Calendar.getInstance().getTime()));
        }
}//GEN-LAST:event_jFormattedTextField4FocusLost

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        DB db = new DB();

        Calendar zdt = ParseDT(jFormattedTextField1.getText(), jFormattedTextField2.getText());
        if (zdt == null) {
            JOptionPane.showMessageDialog(null, "Необходимо указать дату и время поступления заявки.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            return;
        }
        String szdt = getDBTime(zdt);

        String zdone = "false";
        String szcdt = "null";
        if (jCheckBox1.isSelected()) {
            zdone = "true";
            Calendar zcdt = ParseDT(jFormattedTextField3.getText(), jFormattedTextField4.getText());
            if (zcdt != null) {
                szcdt = getDBTime(zcdt);
            } else {
                zcdt = ParseDT(jFormattedTextField3.getText(), "00:00");
                if (zcdt != null) {
                    szcdt = getDBTime(zcdt);
                }
            }
        }

        if (jTextArea1.getText().length() == 0) {
            JOptionPane.showMessageDialog(null, "Необходимо указать текст заявки.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            jTextArea1.requestFocus();
            return;
        }
        String ztext = Vars.getHexString(jTextArea1.getText());

        if (jComboBox1.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(null, "Необходимо указать объект.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            jComboBox1.requestFocus();
            return;
        } else {
            if (jComboBox1.getSelectedItem().toString().length() == 0) {
                JOptionPane.showMessageDialog(null, "Необходимо указать объект.", "Внимание!", JOptionPane.WARNING_MESSAGE);
                jComboBox1.requestFocus();
                return;
            }
        }

        if (jComboBox2.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(null, "Необходимо указать службу.", "Внимание!", JOptionPane.WARNING_MESSAGE);
            jComboBox2.requestFocus();
            return;
        } else {
            if (jComboBox2.getSelectedItem().toString().length() == 0) {
                JOptionPane.showMessageDialog(null, "Необходимо указать службу.", "Внимание!", JOptionPane.WARNING_MESSAGE);
                jComboBox2.requestFocus();
                return;
            }
        }

        Integer zobj = null;
        if (jComboBox1.getSelectedItem().getClass() == z_Object.class) {
            z_Object zo = (z_Object) jComboBox1.getSelectedItem();
            zobj = zo.getK();
        } else {
            Boolean checked = false;
            for (int i = 0; i < jComboBox1.getItemCount(); i++) {
                z_Object o = (z_Object) jComboBox1.getItemAt(i);
                if (o.getObjname().equals(jComboBox1.getSelectedItem().toString())) {
                    checked = true;
                    zobj = o.getK();
                }
            }
            if (!checked) {
                Boolean found = false;
                ResultSet rs = db.getResultSet("SELECT k, objname FROM objects");
                try {
                    while (rs.next()) {
                        if (jComboBox1.getSelectedItem().toString().equals(Vars.getStringFromHex(rs.getString("objname")))) {
                            zobj = rs.getInt("k");
                            found = true;
                        }
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(EditZDialog.class.getName()).log(Level.SEVERE, null, ex);
                }
                db.closeResultSet();
                if (!found) {
                    zobj = db.executeNonQueryAI("INSERT INTO objects (objname, hide) VALUES (\"" + Vars.getHexString(jComboBox1.getSelectedItem().toString()) + "\", 0)");
                }
            }
        }

        Integer zsrv = null;
        if (jComboBox2.getSelectedItem().getClass() == z_Service.class) {
            z_Service zs = (z_Service) jComboBox2.getSelectedItem();
            zsrv = zs.getK();
        } else {
            Boolean checked = false;
            for (int i = 0; i < jComboBox2.getItemCount(); i++) {
                z_Service o = (z_Service) jComboBox2.getItemAt(i);
                if (o.getServicename().equals(jComboBox2.getSelectedItem().toString())) {
                    checked = true;
                    zsrv = o.getK();
                }
            }
            if (!checked) {
                Boolean found = false;
                ResultSet rs = db.getResultSet("SELECT k, servicename FROM services");
                try {
                    while (rs.next()) {
                        if (jComboBox2.getSelectedItem().toString().equals(Vars.getStringFromHex(rs.getString("servicename")))) {
                            zsrv = rs.getInt("k");
                            found = true;
                        }
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(EditZDialog.class.getName()).log(Level.SEVERE, null, ex);
                }
                db.closeResultSet();
                if (!found) {
                    zsrv = db.executeNonQueryAI("INSERT INTO services (servicename, hide) VALUES (\"" + Vars.getHexString(jComboBox2.getSelectedItem().toString()) + "\", 0)");
                }
            }
        }

        String zprim = Vars.getHexString(jTextArea2.getText());

        String zalert = "false";
        if (jCheckBox2.isSelected()) {
            zalert = "true";
        }

        db.executeNonQuery("UPDATE zmain SET " +
                "zdatetime = " + szdt + ", " +
                "zobject = " + zobj.toString() + ", " +
                "ztext = '" + ztext + "', " +
                "zservice = " + zsrv.toString() + ", " +
                "zprim = '" + zprim + "', " +
                "zalert = " + zalert + ", " +
                "zdone = " + zdone + ", " +
                "zdonedt = " + szcdt + ", " +
                "hide = false WHERE k = " + zzo.getK().toString());

        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        FillAll();
        jFormattedTextField1.requestFocus();
    }//GEN-LAST:event_jButton5ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JFormattedTextField jFormattedTextField2;
    private javax.swing.JFormattedTextField jFormattedTextField3;
    private javax.swing.JFormattedTextField jFormattedTextField4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    // End of variables declaration//GEN-END:variables
}
